package com.second.oa.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;


public class DataBaseUtils {
	/**
	 * 获取链接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "oa", "abc123");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new SQLException("找不到数据库驱动", e);
		}
	}
	
	/**
	 * 关闭链接
	 * @param conn
	 * @param sta
	 * @param res
	 * @throws SQLException 
	 */
	public static void close(Connection conn, Statement sta, ResultSet res) throws SQLException {
		if(res != null) {
			res.close();
		}
		if(sta != null) {
			sta.close();
		}
		if(conn != null) {
			conn.close();
		}
	}
	
	/**
	 * 关闭连接
	 * @param conn
	 * @throws SQLException
	 */
	public static void close(Connection conn) throws SQLException {
		close(conn, null);
	}
	/**
	 * 重载的关闭链接
	 * @param conn
	 * @param sta
	 * @throws SQLException 
	 */
	public static void close(Connection conn, Statement sta) throws SQLException {
		close(conn, sta, null);
	}
	
	/**
	 * 执行更新语句
	 * @param sql
	 * @param params
	 * @throws SQLException 
	 */
	public static void executeUpdate(String sql, Object[] params) throws SQLException {
		
		Connection conn = null;
		PreparedStatement sta = null;
		try{
			//conn = getConnection();
			sta = conn.prepareStatement(sql);
			
			// 设置参数
			if(params != null && params.length > 0) {
				for(int i=0;i<params.length;i++) {
					
					Object p = params[i];
					if(p instanceof java.util.Date) {
						// 将util.Date转成sql.Date
						params[i] = new java.sql.Date(((java.util.Date) p).getTime());
					}	
					
					sta.setObject(i + 1, params[i]);
				}
			}
			
			// 执行
			sta.executeUpdate();
		} finally {
			close(null, sta);
		}
		
	}
	
	/**
	 * 重载的更新操作
	 * @param sql
	 * @param params
	 * @throws SQLException
	 */
	public static void executeUpdate(String sql, List<Object> params) throws SQLException {
		executeUpdate(sql, params.toArray());
	}
}